/**
 * 
 */
package it.fuesi.myseries.api.tasks;

import it.fuesi.myseries.api.AbstractApiTask;
import it.fuesi.myseries.model.Episode;
import it.fuesi.myseries.model.MySeriesConstant;
import it.fuesi.myseries.model.Season;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;

/**
 * @author fuesi
 *
 */
public class GetSeasons extends AbstractApiTask {


	@Override
	protected Map<String, String> getApiParams() {
		final Map<String,String> queryParams = new HashMap<String,String>();
		
		int serieId = getCurrentBundle().getInt(MySeriesConstant.ID.toString());
		
		queryParams.put("serieId", ""+serieId);
		
		return queryParams;
		
	}

	@Override
	protected Bundle processResults(JSONObject response) throws JSONException{
		final Bundle results = super.processResults(response);
		
		final Bundle data = new Bundle();
		
		if(results.getBoolean(MySeriesConstant.SUCCESS.toString())){
			final JSONObject map = response.getJSONObject("data"); //FIXME
			
			for(Iterator<String> it = map.keys(); it.hasNext(); ){
				String seasonKey = it.next();
				final JSONObject obj = map.getJSONObject(seasonKey);
				Season s = new Season();
				s.setNumber(obj.getInt("number"));
				
				final JSONObject episodes = obj.getJSONObject("episodes");
				for(Iterator<String> it2 = episodes.keys(); it2.hasNext(); ){
					final String episodeKey = it2.next();
					final JSONObject episode = episodes.getJSONObject(episodeKey);
					Episode e = new Episode();
					e.setName(episode.getString("title"));
					e.setNumber(episode.getInt("number"));
					e.setSeason(s);
					s.addEpisode(e);
				}
				
				data.putSerializable(""+s.getNumber(), s);
			}
		}
		
		results.putBundle(MySeriesConstant.DATA.toString(), data);
		
		return results;
	}

}
